package com.ruoyi.web.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.otc.domain.BazaarRegulator;
import com.ruoyi.otc.domain.Business;
import com.ruoyi.otc.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


/**
 * 任务调度
 */
@Slf4j
@Component("InitBusinessTask")
public class InitBusinessTask {

    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IBazaarRegulatorService bazaarRegulatorService;

    @Value("${gssx.labelAccessKeyId}")
    private String labelAccessKeyId;

    @Value("${gssx.labelUrl}")
    private String labelUrl;

    @Value("${gssx.labelUrl2}")
    private String labelUrl2;

    @Value("${gssx.governmentUrl}")
    private String governmentUrl;


    private static Logger logger = LoggerFactory.getLogger(InitBusinessTask.class);

    public void initBusiness(){
        log.info("初始化企业定时任务开始==========");
        String body = HttpRequest.post(governmentUrl)
                .header("accessKeyId", labelAccessKeyId)
                .header("Content-Type", "application/json")
                .timeout(20000)
                .execute().body();

        JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
        JSONArray legalList= data.getJSONArray("legalList");
        JSONArray companyList = data.getJSONArray("companyList");
        for (Object o : legalList) {
            JSONObject jo = (JSONObject) o;
            Business business = new Business();
            business.setEntname(jo.getString("marketEntities"));
            business.setUniscid(jo.getString("shNumber"));
            // 营业执照号与信用代码保持一致
            business.setLicenceentity(jo.getString("shNumber"));
            for (Object o1 : companyList) {
                JSONObject companyJo = (JSONObject) o1;
                String institutionCode = companyJo.getString("institutionCode");
                if (business.getUniscid().equals(institutionCode)){
                    business.setEnttypeCn(companyJo.getString("companyTape"));
                    //登记机关
                    business.setRegorgCn(companyJo.getString("institution"));
                    //登记日期
                    business.setApprdate(companyJo.getString("dateApproval"));
                    //法定代表人
                    business.setName(companyJo.getString("frName"));
                    //注册资本
                    business.setRegcap(companyJo.getString("longinCapital"));
                    //住所
                    business.setDom(companyJo.getString("abode"));
                    //成立日期
                    business.setEstdate(companyJo.getString("setDate"));
                    //经营(驻在)期限自
                    business.setOpfrom(companyJo.getString("businessStart"));
                    //经营(驻在)期限至
                    business.setOpto(companyJo.getString("businessEnd"));
                    //经营范围/业务范围
                    business.setOpscope(companyJo.getString("businessScope"));
                    business.setUpdateTime(new Date());
                    QueryWrapper<Business> wrapper = new QueryWrapper<Business>().eq("entname", business.getEntname()).eq("uniscid", business.getUniscid());
                    Business one = businessService.getOne(wrapper);
                    if (ObjectUtils.isNotEmpty(one)){
                        businessService.update(business,wrapper);
                    }else {
                        business.setCreateTime(new Date());
                        businessService.save(business);
                    }
                    //拉取标签并保存
                    pullLabel(business);
                    pullLabel2(business);
                }
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        JSONObject jsonObject = JSONObject.parseObject(body);
        List<BazaarRegulator> list;
        JsonNode rootNode;

        try {

            // 解析 JSON 字符串为 JsonNode 对象
            rootNode = objectMapper.readTree(jsonObject.getJSONObject("data").toString());
            JsonNode node = rootNode.get("bazaarRegulatorList");

            list = objectMapper.readValue(node.toString(), objectMapper.getTypeFactory().constructCollectionType(List.class, BazaarRegulator.class));

            for (BazaarRegulator bazaarRegulator : list) {
//                int count = bazaarRegulatorService.count(new QueryWrapper<BazaarRegulator>().eq("ent_name", bazaarRegulator.getEntName())
//                        .eq("ent_id", bazaarRegulator.getEntId()));
//                if (count == 0){
//                    bazaarRegulatorService.save(bazaarRegulator);
                    List<Business> businesses = businessService.list(new QueryWrapper<Business>().eq("entname", bazaarRegulator.getEntName()));
                    if (businesses.size()>0){
                        businesses.get(0).setDomDistrict(bazaarRegulator.getDomDistrict());
                        businesses.get(0).setIndustryCo(bazaarRegulator.getIndustryCo());
                        businessService.updateBusiness(businesses.get(0));
                    }
//                }
            }
            log.info("初始化企业定时任务结束==========");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //拉取政务数据标签
    private void pullLabel(Business business){

        String body = HttpRequest.post(labelUrl)
                .header("accessKeyId", labelAccessKeyId)
                .form("entname",business.getEntname())
                .form("uniscid",business.getUniscid())
                .timeout(20000)
                .execute().body();
        System.out.println("政务数据标签返回："+body);
        if (JSONObject.parseObject(body).getString("code").equals("200")){
            JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
            business.setExist("1".equals(data.getString("exist")));
            business.setLonginCapital("1".equals(data.getString("longinCapital")));
            business.setPossess("1".equals(data.getString("possess")));
            business.setRank1("1".equals(data.getString("rank")));
            business.setWheth("1".equals(data.getString("wheth")));
            business.setWhether("1".equals(data.getString("whether")));
            businessService.updateById(business);
        }

    }
    //拉取业务数据标签
    private void pullLabel2(Business business){
        String body = HttpRequest.post(labelUrl2)
                .header("accessKeyId", labelAccessKeyId)
                .form("entname",business.getEntname())
                .form("uniscid",business.getUniscid())
                .timeout(20000)
                .execute().body();
        System.out.println("业务数据标签返回："+body);
        if (JSONObject.parseObject(body).getString("code").equals("200")){
            JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
            business.setQysf("1".equals(data.getString("qysf")));
            business.setZjsf("1".equals(data.getString("zjsf")));
            businessService.updateById(business);
        }

    }
}